package com.inspectortime.webapp.inspector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.axis.utils.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.Employee;
import com.inspectortime.repository.Factory;
import com.inspectortime.repository.Repository;

public class EditEmployeeController extends SimpleFormController {
	
	protected Repository repository;
	protected Factory factory;
	
	protected final static String DO_NOT_VALIDATE_PASSWORD = "NOCHECK";

	/**
	 * Ensure that new password is only validated by the subsequent validator if something is entered
	 */
	protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception {
		
		// First bind request params to command
		super.onBind(request, command);
		
		// Then make sure that password has a value so that subsequent validation won't fail
		Employee employee = (Employee) command;
		if (StringUtils.isEmpty(employee.getPassword())) {
			employee.setPassword(DO_NOT_VALIDATE_PASSWORD);
		}
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {
		
		Employee employee = (Employee) command;
		
		// If the password was originally empty (not entered on form) then don't change it
		if (!employee.getPassword().equals(DO_NOT_VALIDATE_PASSWORD)) {
			employee.setCleartextPassword(employee.getPassword());	
		}		
		employee.save();
		
		return new ModelAndView(getSuccessView(), errors.getModel());
	}
	
	
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}
	
	public void setFactory(Factory factory) {
		this.factory = factory;
	}



}
